//
//  MultiSelectViewController.m
//  mcrmSAAS
//
//  Created by busy life987 on 15-3-12.
//  Copyright (c) 2015年 GuangZhouXuanWu. All rights reserved.
//

#import "MultiSelectViewController.h"

NSString *const MultiSelectViewControllerSelectContentFormatParamKey = @"MultiSelectViewControllerSelectContentFormatParamKey";
NSString *const MultiSelectViewControllerSelectParamKey = @"MultiSelectViewControllerSelectParamKey";
NSString *const MultiSelectViewControllerSelectOptionsParamKey = @"MultiSelectViewControllerSelectOptionsParamKey";
NSString *const MultiSelectViewControllerTitleParamKey = @"MultiSelectViewControllerTitleParamKey";
NSString *const MultiSelectViewControllerPreSelectedItemsParamKey = @"MultiSelectViewControllerPreSelectedItemsParamKey";

@class MultiSelectListCell;

@protocol MultiSelectListCellDelegate <NSObject>

-(void) multiselectListCell:(MultiSelectListCell*)cell clickSelected:(BOOL)selected;

@end

@interface MultiSelectListCell : XUITableViewCell
{
    UILabel *_optionalsLabel;
    XUISelector *_selector;
}

@property(nonatomic, strong)NSString *optionals;
@property(nonatomic, assign)BOOL check;

@property(nonatomic, weak)id<MultiSelectListCellDelegate> delegate;

+(CGFloat)caleHeight;

@end

@implementation MultiSelectListCell

-(id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithReuseIdentifier:reuseIdentifier];
    
    _selector = [[XUISelector alloc] initWithFrame:CGRectMake(10, ([MultiSelectListCell caleHeight]-30)/2, 30, 30) title:nil headImage:[UIImage imageNamed:@"multicheckbox_uncheck.png"] highlightedImage:[UIImage imageNamed:@"multicheckbox_check.png"]];
    [_selector addTarget:self action:@selector(clickSelector:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:_selector];
    
    
    _optionalsLabel = [[UILabel alloc]initWithFrame:CGRectZero];
    _optionalsLabel.backgroundColor = [UIColor clearColor];
    _optionalsLabel.textColor = [UIColor blackColor];
    _optionalsLabel.font = [UIFont systemFontOfSize:16];
    [self.contentView addSubview:_optionalsLabel];
    
    return self;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
    _selector.left = 20;
    _selector.centerY = self.contentView.height/2;
    
    CGSize titleSize = [_optionalsLabel.text stringSizeWithFont:_optionalsLabel.font];
    _optionalsLabel.size = CGSizeMake(titleSize.width, titleSize.height);
    _optionalsLabel.left = _selector.right + 30;
    _optionalsLabel.centerY = self.contentView.height /2;
}

-(void)setOptionals:(NSString *)optionals
{
    _optionalsLabel.text = optionals;
}

-(void)setCheck:(BOOL)check
{
    [_selector setSelected:check animated:NO];
}

-(void)clickSelector:(XUISelector*)selector
{
    [_delegate multiselectListCell:self clickSelected:selector.selected];
}


+(CGFloat)caleHeight
{
    return 50;
}

@end

@interface MultiSelectViewController ()<XUISearchBarDelegate, MultiSelectListCellDelegate>
{
    NSMutableArray *_arData;
    
    NSMutableArray *_selects;
    
    NSArray *_options;
    NSMutableArray *_preselecteditems;
}

@end

@implementation MultiSelectViewController

- (void)viewDidLoad 
{
    _preselecteditems = self.param[MultiSelectViewControllerPreSelectedItemsParamKey];
    _options = self.param[MultiSelectViewControllerSelectOptionsParamKey];
    NSString *title = self.param[MultiSelectViewControllerTitleParamKey];
    
    [self setBackNavigateItemTitle:title.length > 0? title : @"多选" rightItemText:@"确定"];
    
    [super createTableView:XUITabelViewStyleTypePlain|XUITabelViewStyleTypeSearch];
    
    _ctable.separatorExistFollowCell = YES;
    _ctable.searchBar.delegate = self;
    _ctable.searchBar.searchfield.placeholder = @"搜索";
    _ctable.searchBar.searchfield.textInputMaxLength = 20;
    
    [self addKeyboardObserver];
    
    _arData = [NSMutableArray new];
    [_arData removeAllObjects];
    [_arData addObjectsFromArray:_options];
    [_ctable reloadData];
    
    _selects = [NSMutableArray new];
    if (_preselecteditems.count>0) 
    {
        [_selects removeAllObjects];
        [_selects addObjectsFromArray:_preselecteditems];
    }
}

- (void) viewControllerWillDealloc
{
    [super viewControllerWillDealloc];
    
    [self removeObserver];
}


#pragma mark--
#pragma mark-- tableView delegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [MultiSelectListCell caleHeight];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _arData.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MultiSelectListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(cell == nil)
    {
        cell = [[MultiSelectListCell alloc] initWithReuseIdentifier:@"cell"];
        cell.delegate = self;
    }
    NSString *content = [_arData objectAtIndex:indexPath.row];
    cell.szTag = content;
    cell.optionals = content;
    
    cell.check = NO;
    
    for(NSString *s in _selects)
    {
        if([content isEqualToString:s])
        {
            cell.check =YES;
            break;
        }
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    [UIViewController closeKeyBoard];
    
    MultiSelectListCell *cell = (MultiSelectListCell*)[tableView cellForRowAtIndexPath:indexPath];
    
    NSString *tag = cell.szTag;
    if ([_selects containsObject:tag]) {
        cell.check = NO;
        [_selects removeObject:tag];
    }
    else
    {
        cell.check = YES;
        [_selects addObject:tag];
    }
}

-(void)multiselectListCell:(MultiSelectListCell *)cell clickSelected:(BOOL)selected
{
    NSString *tag = cell.szTag;
    if([_selects containsObject:tag])
    {
        [_selects removeObject:tag];
    }
    else
    {
        [_selects addObject:tag];
    }
}



#pragma mark --
#pragma mark -- search

-(BOOL) clearSearchField:(XUISearchBar *)searchbar
{
    return YES;
}

-(void)searchBar:(XUISearchBar *)searchbar textDidChange:(NSString *)searchText
{
    if(searchText.length>0)
    {
        [_arData removeAllObjects];
        for (NSString *s in _options) {
            if([s rangeOfString:searchText].location!= NSNotFound)
            {
                [_arData addObject:s];
            }
        }
        [_ctable reloadData];
    }
    else
    {
        [_arData removeAllObjects];
        [_arData addObjectsFromArray:_options];
        [_ctable reloadData];
    }
}

-(BOOL) searchBarSearchButtonClicked:(XUISearchBar *)searchbar
{
    [UIViewController closeKeyBoard];
    return YES;
}


#pragma mark --
#pragma mark -- nextStep

-(void)clickedRightBarButton:(id)sender
{
    NSUInteger selectedcount = _selects.count;
    NSString *formatcontent;
    if (selectedcount <= 0) 
    {
        //[UIAlertView showInfoMsg:@"请选择"];
        //return;
        formatcontent = @"";
    }
    else
    {
        formatcontent = [NSString stringWithFormat:@"%@", _selects[0]];
        if (selectedcount > 1 && selectedcount < _options.count)
        {
            formatcontent = [NSString stringWithFormat:@"%@等%@个选项", _selects[0], @(selectedcount)];
        }
        else if (selectedcount == _options.count)
        {
            formatcontent = @"全部";
        }
    }
    
    XUIViewControllerSwitchParam * p = [XUIViewControllerSwitchParam new];
    p.param[MultiSelectViewControllerSelectContentFormatParamKey] = formatcontent;
    p.param[MultiSelectViewControllerSelectParamKey] = _selects;

    [XUINavigationController popWithSwitchParam:p];
}

@end
